using Elsa;
using Elsa.Persistence.EntityFramework.Core.Extensions;
using Elsa.Persistence.EntityFramework.Sqlite;
using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Configuration;

namespace FurionWithElsa.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            var elsaSection = App.Configuration.GetSection("Elsa");

            var server = App.Configuration.GetValue<string>("Elsa:server:BaseUrl");

            services.AddMvc();
            services.AddControllers();

            // Elsa services.
            services
                .AddElsa(elsa => elsa
                    .UseEntityFrameworkPersistence(ef => ef.UseSqlite())
                    .AddConsoleActivities()
                    .AddHttpActivities(elsaSection.GetSection("Server").Bind)
                    .AddQuartzTemporalActivities()
                    .AddJavaScriptActivities()
                    .AddWorkflowsFrom<Startup>()
                );

            // Elsa API endpoints.
            services.AddElsaApiEndpoints();
            services.AddCors(cors => cors.AddDefaultPolicy(policy => policy
                      .AllowAnyHeader()
                      .AllowAnyMethod()
                      .AllowAnyOrigin()
                      )
             );

            // For Dashboard.   
            services.AddRazorPages().AddInjectBase();
            services.AddServerSideBlazor();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseApiVersioning();
            app.UseHttpActivities();
            app.UseRouting();
       
            app.UseInjectBase();

            app.UseEndpoints(endpoints =>
            {
                // Elsa API Endpoints are implemented as regular ASP.NET Core API controllers.
                endpoints.MapBlazorHub();

                endpoints.MapControllers();
           
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}